import { useState, useEffect, useMemo } from 'react';
import copy from 'copy-to-clipboard';
import { message } from 'antd';
import { COLLAPSE_CONTENT_TYPE } from '@/utils/enum';
import useNativeSQL from '@/hooks/useNativeSQL';
import { usePreviewBreakdownDataMutation } from '@/apollo/client/graphql/home.generated';
import { saveAs } from 'file-saver';

const getTextButton = (isActive: boolean) => ({
  type: 'text',
  className: `d-inline-flex align-center mr-2 ${isActive ? 'gray-9' : 'gray-6'}`,
});

function getButtonsProps({
  isLastStep,
  isPreviewData,
  isViewSQL,
  previewDataProps,
  onViewSQL,
  onPreviewData,
}: {
  isLastStep: boolean;
  isPreviewData: boolean;
  isViewSQL: boolean;
  previewDataProps: { loading: boolean };
  onViewSQL: () => void;
  onPreviewData: () => Promise<void>;
}) {
  const previewDataButtonText = 'Prevew data';
  const viewSQLButtonText = isLastStep ? 'View full SQL' : 'View SQL';
  const previewDataButtonProps = isLastStep
    ? { type: 'primary', className: 'mr-2' }
    : getTextButton(isPreviewData);
  const viewSQLButtonProps = isLastStep ? {} : getTextButton(isViewSQL);

  return {
    viewSQLButtonProps: {
      ...viewSQLButtonProps,
      children: viewSQLButtonText,
      onClick: onViewSQL,
    },
    previewDataButtonProps: {
      ...previewDataButtonProps,
      children: previewDataButtonText,
      loading: previewDataProps.loading,
      onClick: onPreviewData,
    },
  };
}

export default function useAnswerStepContent({
  fullSql,
  isLastStep,
  sql,
  stepIndex,
  threadResponseId,
}: {
  fullSql: string;
  isLastStep: boolean;
  sql: string;
  stepIndex: number;
  threadResponseId: number;
}) {
  const { fetchNativeSQL, nativeSQLResult } = useNativeSQL();

  const [collapseContentType, setCollapseContentType] =
    useState<COLLAPSE_CONTENT_TYPE>(COLLAPSE_CONTENT_TYPE.NONE);

  const [previewData, previewDataResult] = usePreviewBreakdownDataMutation({
    onError: (error) => console.error(error),
  });

  const onViewSQL = () =>
    setCollapseContentType(COLLAPSE_CONTENT_TYPE.VIEW_SQL);

  const onPreviewData = async () => {
    setCollapseContentType(COLLAPSE_CONTENT_TYPE.PREVIEW_DATA);
    nativeSQLResult.setNativeSQLMode(false);
    await previewData({
      variables: { where: { responseId: threadResponseId, stepIndex } },
    });
    console.log('预览数据结果:', {
      data: previewDataResult.data,
      previewBreakdownData: previewDataResult.data?.previewBreakdownData,
      keys: previewDataResult.data?.previewBreakdownData
        ? Object.keys(previewDataResult.data.previewBreakdownData[0] || {})
        : [],
    });
  };

  const onCloseCollapse = () => {
    setCollapseContentType(COLLAPSE_CONTENT_TYPE.NONE);
    nativeSQLResult.setNativeSQLMode(false);
  };

  const onCopyFullSQL = () => {
    copy(nativeSQLResult.nativeSQLMode ? nativeSQLResult.data : fullSql);
    message.success('Copied SQL to clipboard.');
  };

  const onChangeNativeSQL = async (checked: boolean) => {
    nativeSQLResult.setNativeSQLMode(checked);
    checked && fetchNativeSQL({ variables: { responseId: threadResponseId } });
  };

  const onDownloadCSV = () => {
    // 优先使用格式化后的数据，如果不可用则尝试使用原始数据
    const formattedData = formattedPreviewData;
    const rawData = previewDataResult?.data?.previewBreakdownData;

    console.log('CSV下载数据源:', {
      formattedData,
      rawData,
      hasFormattedData: !!formattedData,
    });

    // 首先尝试处理格式化的数据
    if (
      formattedData &&
      formattedData.columns &&
      Array.isArray(formattedData.data)
    ) {
      try {
        const headers = formattedData.columns.map((col) => col.name);

        // 将二维数组转换为CSV
        const csvContent = [
          headers.join(','), // CSV标题行
          ...formattedData.data.map((row) =>
            row
              .map((value) =>
                value != null ? `"${String(value).replace(/"/g, '""')}"` : '""',
              )
              .join(','),
          ),
        ].join('\n');

        // 创建并下载CSV文件
        const blob = new Blob([csvContent], {
          type: 'text/csv;charset=utf-8;',
        });
        saveAs(
          blob,
          `preview_data_${new Date().toISOString().replace(/:/g, '-')}.csv`,
        );
        return;
      } catch (error) {
        console.error('处理格式化数据时出错:', error);
      }
    }

    // 如果格式化数据不可用或处理失败，尝试处理原始数据
    if (rawData) {
      try {
        let processedData = rawData;
        let headers = [];

        // 处理不同的数据格式
        if (Array.isArray(rawData)) {
          if (rawData.length === 0) {
            message.warning('No data available to download.');
            return;
          }

          const firstRow = rawData[0];
          if (firstRow && typeof firstRow === 'object') {
            headers = Object.keys(firstRow);
            processedData = rawData;
          }
        } else if (
          typeof rawData === 'object' &&
          rawData.data &&
          Array.isArray(rawData.data)
        ) {
          if (rawData.columns && Array.isArray(rawData.columns)) {
            headers = rawData.columns.map((col) => col.name || String(col));
          } else {
            const firstRow = rawData.data[0];
            if (Array.isArray(firstRow) && rawData.data.length > 0) {
              // 如果没有列名，使用列索引
              headers = firstRow.map((_, index) => `Column ${index + 1}`);
            }
          }
          processedData = rawData.data;
        }

        if (headers.length === 0) {
          message.warning('No columns found in the data');
          return;
        }

        // 生成CSV内容
        let csvContent;

        if (Array.isArray(processedData[0])) {
          // 已经是二维数组格式
          csvContent = [
            headers.join(','),
            ...processedData.map((row) =>
              row
                .map((value) =>
                  value != null
                    ? `"${String(value).replace(/"/g, '""')}"`
                    : '""',
                )
                .join(','),
            ),
          ].join('\n');
        } else {
          // 对象数组格式
          csvContent = [
            headers.join(','),
            ...processedData.map((row) =>
              headers
                .map((header) => {
                  const value = row[header];
                  return value != null
                    ? `"${String(value).replace(/"/g, '""')}"`
                    : '""';
                })
                .join(','),
            ),
          ].join('\n');
        }

        // 创建并下载CSV文件
        const blob = new Blob([csvContent], {
          type: 'text/csv;charset=utf-8;',
        });
        saveAs(
          blob,
          `preview_data_${new Date().toISOString().replace(/:/g, '-')}.csv`,
        );
      } catch (error) {
        console.error('Error generating CSV:', error);
        message.error('Failed to generate CSV file');
      }
    } else {
      message.warning('No data available to download.');
    }
  };

  const isViewSQL = collapseContentType === COLLAPSE_CONTENT_TYPE.VIEW_SQL;
  const isPreviewData =
    collapseContentType === COLLAPSE_CONTENT_TYPE.PREVIEW_DATA;
  const previewDataLoading = previewDataResult.loading;
  const answerButtonsProps = getButtonsProps({
    isLastStep,
    isPreviewData,
    isViewSQL,
    onPreviewData,
    onViewSQL,
    previewDataProps: {
      loading: previewDataLoading,
    },
  });
  const isViewFullSQL = isLastStep && isViewSQL;
  const displayedSQL = isLastStep ? fullSql : sql;

  useEffect(() => {
    // 当获取到预览数据后，检查数据格式并打印日志
    if (previewDataResult?.data?.previewBreakdownData) {
      console.log('预览数据已加载:', {
        data: previewDataResult.data.previewBreakdownData,
        type: typeof previewDataResult.data.previewBreakdownData,
        isArray: Array.isArray(previewDataResult.data.previewBreakdownData),
        firstItem: previewDataResult.data.previewBreakdownData[0],
        headers: previewDataResult.data.previewBreakdownData[0]
          ? Object.keys(previewDataResult.data.previewBreakdownData[0])
          : [],
      });
    }
  }, [previewDataResult?.data]);

  // 格式化预览数据，使其符合PreviewData组件的要求
  const formattedPreviewData = useMemo(() => {
    const rawData = previewDataResult?.data?.previewBreakdownData;
    console.log('格式化数据源:', rawData);

    // 特别处理：检查预览数据是否已经有columns和data结构
    if (
      rawData &&
      typeof rawData === 'object' &&
      !Array.isArray(rawData) &&
      rawData.columns &&
      Array.isArray(rawData.data)
    ) {
      console.log('使用已有的列和数据结构');
      return rawData;
    }

    if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
      console.log('无有效数据，返回undefined');
      return undefined;
    }

    // 从第一行数据提取列信息
    const firstRow = rawData[0];
    if (!firstRow || typeof firstRow !== 'object') {
      console.log('无效的第一行数据', firstRow);
      return undefined;
    }

    const headers = Object.keys(firstRow);
    if (headers.length === 0) {
      console.log('没有找到列标题');
      return undefined;
    }

    // 推断每列的数据类型
    const columns = headers.map((header) => {
      const sampleValue = firstRow[header];
      const type =
        typeof sampleValue === 'number'
          ? 'number'
          : typeof sampleValue === 'boolean'
            ? 'boolean'
            : 'string';
      return { name: header, type };
    });

    // 格式化数据为二维数组
    const data = rawData.map((row) => headers.map((header) => row[header]));

    console.log('已处理数据:', { columns, data });
    return {
      columns,
      data,
    };
  }, [previewDataResult?.data?.previewBreakdownData]);

  return {
    ...answerButtonsProps,
    collapseContentProps: {
      isPreviewData,
      isViewSQL,
      isViewFullSQL,
      sql: displayedSQL,
      previewDataResult: {
        error: previewDataResult.error,
        loading: previewDataLoading,
        previewData: formattedPreviewData,
      },
      nativeSQLResult,
      onCopyFullSQL,
      onCloseCollapse,
      onChangeNativeSQL,
      onDownloadCSV,
    },
  };
}
